package client.comm.baoding.ui.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.paging.*
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.utils.StoreUtil
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.api.bean.Zcjl
import client.comm.baoding.ui.viewmodel.MiddleVm
import kotlinx.coroutines.flow.Flow
import java.lang.Exception


class DaySignViewModel(app: Application) : MiddleVm(app) {
    val isShowing = MutableLiveData<Boolean>(false)
    val isSign = MutableLiveData<Boolean>(false)
    val isLoadMore = MutableLiveData<Boolean>(false)
    val sign = MutableLiveData<Int>(0)

    val startCall = MutableLiveData<JsonResult<Ret>>()
    val callUser = MutableLiveData<JsonResult<UserInfo>>()

    fun userInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data!!)
                    }
                }
            }
        }, success = {
            callUser.value = it
        })
    }

    fun start() {
        isShowing.value = true
        isSign.value = true
        hold({
            server.user_sign_in()
        }, success = {
            startCall.value = it
        }, complete = {
            isShowing.value = false
        }, err = {
            isSign.value = false
        })
    }

    fun pagingDataUser(): Flow<PagingData<Zcjl.Record>> {
        return Pager(
            config = PagingConfig(pageSize = 10),
            pagingSourceFactory = {
                object : PagingSource<Int, Zcjl.Record>() {
                    override fun getRefreshKey(state: PagingState<Int, Zcjl.Record>): Int? =
                        null

                    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Zcjl.Record> {
                        return try {
                            val page = params.key ?: 1
                            val ret = server.zcjl(page,15)
                            if (ret.body() != null && ret.body()!!.isSuccess) {
                                val list = ret.body()!!.data!!.record_list
                                val pPage = if (page > 1) page - 1 else null
                                val nextKey = if (list.size >= 10) page + 1 else null
                                LoadResult.Page(list, pPage, nextKey)
                            } else
                                LoadResult.Error(Exception("网络错误"))
                        } catch (e: Exception) {
                            LoadResult.Error(e)
                        }
                    }
                }
            }
        ).flow
    }
}